package com.yurun.orgbranch.service.Impl;

import com.yurun.commonapi.pojo.Branch;
import com.yurun.commonapi.pojo.Employee;
import com.yurun.commonapi.pojo.UmsRole;
import com.yurun.employeemodule.mapper.EmployeeMapper;
import com.yurun.orgpermissionmodule.mapper.OrgPermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.yurun.orgbranch.mapper.BranchMapper;
import com.yurun.orgbranch.service.BranchService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author lihao
 * @mail lihaohaocn@gmail.com
 * @Date 2021/8/18 11:04 下午
 */
@Service
@Transactional
public class BranchServiceImpl implements BranchService {
    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrgPermissionMapper permissionModuleMapper;


    @Override
    public List<Branch> getAllBranch() {
        return branchMapper.getAllBranch();
    }

    @Override
    public List<Branch> getBranchByName(String branchName, BigInteger employeeId) {
        return branchMapper.getBranchByName(branchName, employeeId);
    }

    @Override
    public List<Branch> getAllBranchInfoByOrgId(BigInteger employeeId) {
        return branchMapper.getAllBranchInfoByOrgId(employeeId);
    }

    @Override
    public List<Branch> getBranchOption(BigInteger organizationId) {
        return branchMapper.getBranchOption(organizationId);
    }

    @Override
    public List<Branch> getBranchList(String keyword, BigInteger employeeId) {
        if (!keyword.equals("") && keyword != null){
            return branchMapper.getBranchByName(keyword, employeeId);
        }
        return branchMapper.getAllBranchInfoByOrgId(employeeId);

    }

    @Override
    public int delBranchById(Branch branch) {

        Date time = new Date();
        try {
            branchMapper.delBranchByBranchId(branch.getOrganizationId(), time, branch.getBranchId());
            branchMapper.delEmployeeByOrgId(branch.getOrganizationId(), time, branch.getBranchId());
            branchMapper.delTeacherByOrgId(branch.getOrganizationId(), time, branch.getBranchId());
            branchMapper.delStudentByOrgId(branch.getOrganizationId(), time, branch.getBranchId());
            return 1;
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    @Transactional
    public boolean addBranch(Branch branch) {
        branch.setCreateTime(new Date());
        branch.setUpdateTime(new Date());
        // 生成分店id
        BigInteger branchId = getBranchId();
        BigInteger organizationId = branch.getOrganizationId();
        BigInteger flag_branchId = branchMapper.verifyBranchIdIsRepeat(branchId);
        // 判断是否已存在该员工id
        while (flag_branchId != null) {  // 已存在
            branchId = getBranchId();
            flag_branchId = branchMapper.verifyBranchIdIsRepeat(branchId);
        }
        branch.setBranchId(branchId);
        BigInteger count = branchMapper.getBranchCount(branch.getOrganizationId());

        Employee employee = new Employee();
        // 生成员工id
        BigInteger employeeId = getEnumId(String.valueOf(branch.getOrganizationId()).substring(0, 6));
        Integer flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        // 判断是否已存在该员工id
        while (flag_employeeId != null) {  // 已存在
            employeeId = getEnumId(String.valueOf(branch.getOrganizationId()).substring(0, 6));
            flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        }


        // 创建员工
        employee.setEmployeeId(employeeId);
        employee.setOrganizationId(organizationId);
        employee.setEmployeePwd(setMD5PWD("123456"));
        employee.setEmployeeName("分店经理");
        employee.setBranchId(branchId);
        employee.setEmployeeAddress(branch.getBranchAddress());
        employee.setEmployeeArea(branch.getBranchArea());
        employee.setEmployeeCity(branch.getBranchCity());
        employee.setEmployeePlace(branch.getBranchPlace());
        employee.setEmployeeIcon(branch.getBranchIcon());
        employee.setEmployeeIdcard(branch.getBranchPrincipalIdcard());
        employee.setEmployeeIdcardNumber(branch.getBranchPrincipalIdcardNumber());
        employee.setEmployeePhone(branch.getBranchPrincipalPhone());
        employee.setEmployeePosition("9");
        employee.setEmployeeProvince(branch.getBranchProvince());
        employee.setEmployeeSex(0);
        employee.setIsDel(0);
        employee.setStatus(1);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        try {
            // 新增员工
            employeeMapper.addEmployee(employee);

            int roleId = branchMapper.getRoleIdByOrgIdAndRoleName(organizationId, "分店经理"); // 获取roleId
            // 给员工增加角色
            permissionModuleMapper.addEmployeeRole(roleId, employeeId);

            branchMapper.editBranchCount(branch.getOrganizationId(), count.add(BigInteger.valueOf(1)));
            branchMapper.addBranch(branch);
            return true;
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public int editBranch(Branch branch) {
        branch.setUpdateTime(new Date());
        return branchMapper.editBranch(branch);
    }

    @Override
    public Branch getBranchInfoById(BigInteger organizationId, BigInteger branchId) {
        return branchMapper.getBranchInfoById(organizationId, branchId);
    }

    public BigInteger getEnumId(String placeNum) {
        Random random = new Random();
        StringBuilder result= new StringBuilder();
        for (int i=0;i<6;i++)
        {
            result.append(random.nextInt(10));
        }
        return BigInteger.valueOf(Long.parseLong(placeNum + result));
    }

    public BigInteger getBranchId() {
        Random random = new Random();
        StringBuilder result= new StringBuilder();
        for (int i=0;i<4;i++)
        {
            result.append(random.nextInt(10));
        }
        return BigInteger.valueOf(Long.parseLong(String.valueOf(result)));
    }

    @Transactional
    public int addRole(BigInteger organizationId, String roleName) {
        // 新增角色
        UmsRole role = new UmsRole();
        role.setOrganizationId(organizationId);
        role.setStatus(1);
        role.setDescription(roleName);
        role.setName(roleName);
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        permissionModuleMapper.addRole(role); // 增加角色

        return role.getId();
    }

    @Transactional
    public void addMenu(int roleId, List<Integer> array) {
        for (int i = 0; i < array.size(); i++) {
            // 增加菜单
            permissionModuleMapper.addMenuByRoleId(roleId, array.get(i));
        }
    }

    @Transactional
    public void addPermission(int roleId, int[] arr) {
        // 增加权限
        for (int value : arr) {
            for (int list : branchMapper.getAdminAllPermission(value)) {
                permissionModuleMapper.addPermissionByRoleId(roleId, list);
            }

        }
    }

    public void addPermission(int roleId, List<Integer> arr) {
        // 增加权限
        for (int value : arr) {
            permissionModuleMapper.addPermissionByRoleId(roleId, value);
        }
    }

    public String setMD5PWD(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}
